package club.itstudio.itouc.controller.jw.stu

import club.itstudio.itouc.core.exception.ITOUCException
import club.itstudio.itouc.core.util.Result
import club.itstudio.itouc.core.util.ResultUtil
import club.itstudio.itouc.service.JwOps
import club.itstudio.itouc.util.Redis
import org.springframework.web.bind.annotation.CookieValue
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RestController

@RestController
class RequiredCredit (val jwOps: JwOps,
                      val redis: Redis){

    @GetMapping("/jw/stu/requiredcredit")
    fun requiredCredit(@CookieValue token: String): Result<Any> {
        val session = jwOps.getJwSession(token)
        val credits =  try {
            redis.getRequiredCredit(session.userCode)
        }catch (e: ITOUCException) {
            session.refresh()
            jwOps.getRequiredCredits(session).also {
                redis.saveRequiredCredit(session.userCode, it)
            }
        }
        return ResultUtil.success(credits)
    }
}